﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services.Interface.MaterialDisposal;
using AutoMapper;
using Ganss.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using NPOI.SS.Formula.Functions;
using RndMaterialDisposalService.Services;
using Razor.Templating.Core;
using RndMaterialDisposalService.Services.Interface;

namespace RndMaterialDisposalService.Controllers.MaterialDisposal
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class MaterialDisposalController : ControllerBase
    {

        private readonly string ProcessFullName = "MaterialDisposal\\MaterialDisposal";
        private readonly string SaveFormDataUrl = "/api/WorkflowData/ApplicationData";
        private readonly string ProcessFolioUrl = "/api/WorkflowData/ApplicationNumber";

        private readonly IConfiguration configuration;
        private readonly IMaterialDisposalService materialDisposalService;
        private readonly ILogger<MaterialDisposalController> logger;
        private readonly IWorkflowCommon workflowCommon;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        /// <param name="_configuration"></param>
        /// <param name="_workflowCommon"></param>
        /// <param name="_materialDisposalService"></param>
        public MaterialDisposalController(ILogger<MaterialDisposalController> _logger,
            IConfiguration _configuration,
            IWorkflowCommon _workflowCommon,
            IMaterialDisposalService _materialDisposalService)
        {
            logger = _logger;
            configuration= _configuration;
            workflowCommon = _workflowCommon;
            materialDisposalService = _materialDisposalService;
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID"></param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID)
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var result = new FormInfoResp();
            if (!string.IsNullOrEmpty(procInstID))
            {
                var url = $"{CommonServiceHost}{SaveFormDataUrl}?procInstID={procInstID}";
                result = await HttpHelper.GetAsync<FormInfoResp>(url);
                result.ViewsStatus = "Approval";
                return Ok(result);
            }

            var formDataModel = new MaterialDisposalFormData();
            var url2 = $"{CommonServiceHost}{ProcessFolioUrl}?workflowCode={ProcessFullName}";
            var appNumber = await HttpHelper.GetAsync<string>(url2);
            result.ApplicationNumber = appNumber;
            result.ViewsStatus = "Start";
            result.FormData = JsonSerializer.Serialize(formDataModel, new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            });
            return Ok(result);
        }

        /// <summary>
        /// 保存报表数据
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("SaveReportData")]
        public async Task<IActionResult> SaveReportData(MaterialDisposalFormData formData)
        {
            try
            {
                var result = await materialDisposalService.SaveReportData(formData);
                logger.LogInformation($"新增报表数据,流程主题：{formData.FormHeader.Subject},数量：{result},时间：{DateTime.Now}");
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据,流程主题：{formData.FormHeader.Subject},异常原因：{ex.Message},时间：{DateTime.Now}");
                throw ;
            }
        }

        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("GetReportData")]
        [PageList]
        public async Task<IActionResult> MaterialDisposalReportData(MaterialDisposalReportDataReq inputCondition)
        {
            var data = await materialDisposalService.GetReportData(inputCondition);
            logger.LogInformation($"MaterialDisposalReportData: {data}");
            var result = ApiResponsePageList<MaterialDisposalReportDto>.CreatePageListByResult(data.list, inputCondition.PageIndex, inputCondition.PageSize, data.count);
            return Ok(result);
        }

        /// <summary>
        /// 导出报表文件
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("ReportExport")]
        [PageList]
        public async Task<IActionResult> MaterialDisposalReportExport(MaterialDisposalReportDataReq inputCondition, [FromServices]IMapper mapper)
        {
            inputCondition.PageIndex = 1;
            inputCondition.PageSize = 65535;
            var data = await materialDisposalService.GetExcelReportData(inputCondition);
            //var list = mapper.Map<List<MaterialDisposalReportExportModel>>(data.list);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\研发物料报废电子流{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", data);
            return Ok(filePath);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost("SendEmailNotification")]
        public async Task<IActionResult> SendEmailNotification(InformInformation info)
        {
            try
            {
                if (info != null && info.UserIDList.Count > 0)
                {
                    List<EmailParameter> emaiList = new List<EmailParameter>();
                    info.UserIDList.ForEach((x) => {
                        emaiList.Add(new EmailParameter
                        {
                            ProcInstId = info.ProcInstId,
                            Subject = info.Subject,
                            FunctionId = info.FunctionId,
                            DocumentDistributionUserID = x,
                            ViteFormUrl = info.ViteFormUrl,
                        }); ;
                    });

                    //发送邮件
                    var html = await RazorTemplateEngine.RenderAsync("~/Pages/EmailTemplates/MaterialDisposal/EmailNotification.cshtml");
                    var rndMaterialDisposalHost = configuration.GetSection("RndMaterialDisposalHost").Value;
                    html = html.Replace("[ViteFormUrl]", rndMaterialDisposalHost);
                    workflowCommon.EmailSending(emaiList, html);
                }
                logger.LogInformation($"邮件通知,流程实例号：{info.ProcInstId},标题：{info.Subject},时间：{DateTime.Now}");
                return Ok(true);
            }
            catch (Exception ex)
            {
                logger.LogError($"邮件通知,流程实例号：{info.ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                return Ok(false);
            }
        }

    }
}
